#include "notes.h"

Note::Note(int page, QString text) {
	pageval = page;
	textval = text.replace(QString("<br/>"),QString("\n"),Qt::CaseInsensitive);
	isvalid = true;
}

TextNote::TextNote(int page, QPointF point, QString text) :
	Note(page, text) {
	locationval = point;
}

RectNote::RectNote(int page, QRectF rect, QString text) :
	Note(page, text) {
	rectval = rect;
}

ClickPoint::ClickPoint(TextNote *n) {
	pointval = n->location();
	pnote = n;
}

ClickPoint::ClickPoint(RectNote *r) {
	pointval = r->rectangle().bottomRight();
	pnote = r;
}

void PageNotes::addNote(TextNote *note) {
	textNotesList.append(*note);
}

void PageNotes::addNote(RectNote *note) {
	rectNotesList.append(*note);
}

QList<TextNote>& PageNotes::textNotes() {
	return textNotesList;
}

QList<RectNote>& PageNotes::rectNotes() {
	return rectNotesList;
}

PageNotes* DocumentNotes::getNotesForPage(int page) {
	PageNotes *notes = docNotes.value(page);
	if (!notes)
		notes = new PageNotes();
	return notes;
}

void DocumentNotes::addNote(TextNote *note) {
	PageNotes *notes = docNotes.value(note->page());
	if (!notes)
		notes = new PageNotes();
	notes->addNote(note);
	docNotes.insert(note->page(), notes);
}

void DocumentNotes::addNote(RectNote *note) {
	PageNotes *notes = docNotes.value(note->page());
	if (!notes)
		notes = new PageNotes();
	notes->addNote(note);
	docNotes.insert(note->page(), notes);
}

void DocumentNotes::loadFromFile(const QString &file) {
	QString s = file.trimmed();
	QFile f(s.trimmed());
	f.open(QIODevice::ReadOnly);
	QTextStream stream(&f);

	QString line;
	bool readNotes = 0;
	bool read = 1;
	while (!stream.atEnd() && read) {
		if (readNotes == 0) {
			line = stream.readLine();
			if (line.compare(QString("%%PDF Notes Declaration Start")) == 0) {
				readNotes = 1;
			}
		} else {
			QString str;
			stream >> str;
			if (str.contains(QString("%%PdfTextNote"), Qt::CaseInsensitive)) {
				int p;
				qreal x;
				qreal y;
				stream >> p;
				stream >> x;
				stream >> y;
				QString text = stream.readLine();
				TextNote *n = new TextNote(p, QPointF(x, y), text.trimmed());
				addNote(n);
			} else if (str.contains(QString("%%PdfRectNote"), Qt::CaseInsensitive)) {
				int p;
				qreal x;
				qreal y;
				qreal w;
				qreal h;

				stream >> p;
				stream >> x;
				stream >> y;
				stream >> w;
				stream >> h;
				QString text = stream.readLine();
				RectNote *n = new RectNote(p,QRectF(x,y,w,h),text.trimmed());
				addNote(n);
			} else if (line.compare(QString("%%PDF Notes Declaration Start")) == 0) {
				clear();
			}
		}
	}
	f.close();
}
